using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace demo
{
    /// <summary>
    /// 环境同步助手 - 将FormTest的改动同步到Form1
    /// </summary>
    public static class EnvironmentSyncHelper
    {
        /// <summary>
        /// 文件映射关系
        /// </summary>
        private static readonly Dictionary<string, string> FileMappings = new Dictionary<string, string>
        {
            { "FormTest.cs", "Form1.cs" },
            { "FormTest.Designer.cs", "Form1.Designer.cs" },
            { "FormTest.resx", "Form1.resx" }
        };

        /// <summary>
        /// 内容替换映射
        /// </summary>
        private static readonly Dictionary<string, string> ContentMappings = new Dictionary<string, string>
        {
            { "FormTest", "Form1" },
            { "测试环境", "" },
            { @"\[测试环境\]", "" }
        };

        /// <summary>
        /// 同步选项
        /// </summary>
        public class SyncOptions
        {
            public bool CreateBackup { get; set; } = true;
            public bool ShowProgress { get; set; } = true;
            public bool ConfirmOverwrite { get; set; } = false;
            public bool DryRun { get; set; } = false;
        }

        /// <summary>
        /// 同步结果
        /// </summary>
        public class SyncResult
        {
            public bool Success { get; set; }
            public List<string> ProcessedFiles { get; set; } = new List<string>();
            public List<string> SkippedFiles { get; set; } = new List<string>();
            public List<string> Errors { get; set; } = new List<string>();
            public string BackupDirectory { get; set; }
        }

        /// <summary>
        /// 执行环境同步
        /// </summary>
        /// <param name="options">同步选项</param>
        /// <returns>同步结果</returns>
        public static SyncResult SyncEnvironment(SyncOptions options = null)
        {
            if (options == null)
                options = new SyncOptions();

            var result = new SyncResult();
            
            // 获取项目源代码目录，而不是bin目录
            var baseDir = AppDomain.CurrentDomain.BaseDirectory;
            var projectDir = baseDir;
            
            // 如果当前在bin\Debug目录，则向上找到项目根目录
            if (baseDir.Contains("bin\\Debug") || baseDir.Contains("bin\\Release"))
            {
                var binIndex = baseDir.IndexOf("\\bin\\");
                if (binIndex > 0)
                {
                    projectDir = baseDir.Substring(0, binIndex);
                }
            }

            try
            {
                // 检查源文件是否存在
                var missingFiles = new List<string>();
                foreach (var sourceFile in FileMappings.Keys)
                {
                    var sourcePath = Path.Combine(projectDir, sourceFile);
                    if (!File.Exists(sourcePath))
                    {
                        missingFiles.Add(sourceFile);
                    }
                }

                if (missingFiles.Count > 0)
                {
                    result.Errors.Add($"以下源文件不存在: {string.Join(", ", missingFiles)}");
                    return result;
                }

                // 创建备份目录
                if (options.CreateBackup && !options.DryRun)
                {
                    result.BackupDirectory = Path.Combine(projectDir, $"Backup_{DateTime.Now:yyyyMMdd_HHmmss}");
                    Directory.CreateDirectory(result.BackupDirectory);
                }

                // 同步文件
                foreach (var mapping in FileMappings)
                {
                    var sourceFile = mapping.Key;
                    var targetFile = mapping.Value;
                    var sourcePath = Path.Combine(projectDir, sourceFile);
                    var targetPath = Path.Combine(projectDir, targetFile);

                    try
                    {
                        // 检查是否需要确认覆盖
                        if (File.Exists(targetPath) && options.ConfirmOverwrite && !options.DryRun)
                        {
                            var dialogResult = MessageBox.Show(
                                $"目标文件 {targetFile} 已存在，是否覆盖？",
                                "确认覆盖",
                                MessageBoxButtons.YesNo,
                                MessageBoxIcon.Question);

                            if (dialogResult != DialogResult.Yes)
                            {
                                result.SkippedFiles.Add(targetFile);
                                continue;
                            }
                        }

                        // 备份原文件
                        if (options.CreateBackup && File.Exists(targetPath) && !options.DryRun)
                        {
                            var backupPath = Path.Combine(result.BackupDirectory, targetFile);
                            File.Copy(targetPath, backupPath, true);
                        }

                        // 读取源文件内容
                        var content = File.ReadAllText(sourcePath, Encoding.UTF8);

                        // 应用内容替换
                        foreach (var contentMapping in ContentMappings)
                        {
                            content = Regex.Replace(content, contentMapping.Key, contentMapping.Value);
                        }

                        // 写入目标文件
                        if (!options.DryRun)
                        {
                            File.WriteAllText(targetPath, content, Encoding.UTF8);
                        }

                        result.ProcessedFiles.Add($"{sourceFile} -> {targetFile}");

                        if (options.ShowProgress)
                        {
                            Console.WriteLine($"已同步: {sourceFile} -> {targetFile}");
                        }
                    }
                    catch (Exception ex)
                    {
                        result.Errors.Add($"同步文件 {sourceFile} 时出错: {ex.Message}");
                    }
                }

                result.Success = result.Errors.Count == 0;
            }
            catch (Exception ex)
            {
                result.Errors.Add($"同步过程中出现错误: {ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// 显示同步对话框
        /// </summary>
        public static void ShowSyncDialog()
        {
            var dialogResult = MessageBox.Show(
                "是否要将FormTest的改动同步到Form1？\n\n" +
                "这将会：\n" +
                "1. 自动备份现有的Form1文件\n" +
                "2. 将FormTest的内容复制到Form1\n" +
                "3. 自动替换相关的类名和标识\n\n" +
                "建议在同步前先保存当前工作。",
                "环境同步确认",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question);

            if (dialogResult == DialogResult.Yes)
            {
                var options = new SyncOptions
                {
                    CreateBackup = true,
                    ShowProgress = false,
                    ConfirmOverwrite = false,
                    DryRun = false
                };

                var result = SyncEnvironment(options);

                if (result.Success)
                {
                    var message = $"环境同步完成！\n\n" +
                                 $"已处理文件: {result.ProcessedFiles.Count}\n" +
                                 $"跳过文件: {result.SkippedFiles.Count}\n";

                    if (!string.IsNullOrEmpty(result.BackupDirectory))
                    {
                        message += $"备份目录: {result.BackupDirectory}\n";
                    }

                    message += "\n建议重新编译项目并测试Form1功能。";

                    MessageBox.Show(message, "同步完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    var errorMessage = "同步过程中出现错误：\n\n" + string.Join("\n", result.Errors);
                    MessageBox.Show(errorMessage, "同步失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// 检查是否需要同步
        /// </summary>
        /// <returns>如果FormTest比Form1更新则返回true</returns>
        public static bool NeedSync()
        {
            try
            {
                // 获取项目源代码目录，而不是bin目录
                var baseDir = AppDomain.CurrentDomain.BaseDirectory;
                var projectDir = baseDir;
                
                // 如果当前在bin\Debug目录，则向上找到项目根目录
                if (baseDir.Contains("bin\\Debug") || baseDir.Contains("bin\\Release"))
                {
                    var binIndex = baseDir.IndexOf("\\bin\\");
                    if (binIndex > 0)
                    {
                        projectDir = baseDir.Substring(0, binIndex);
                    }
                }
                
                var formTestPath = Path.Combine(projectDir, "FormTest.cs");
                var form1Path = Path.Combine(projectDir, "Form1.cs");

                if (!File.Exists(formTestPath) || !File.Exists(form1Path))
                    return false;

                var formTestTime = File.GetLastWriteTime(formTestPath);
                var form1Time = File.GetLastWriteTime(form1Path);

                return formTestTime > form1Time;
            }
            catch
            {
                return false;
            }
        }
    }
}